<?php
/**
 * PrimeTable.php
 */

namespace RHX\Model\Table;

use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\ResultSet\ResultSet;
use RHX\Model\Object\Prime;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Expression;

class PrimeTable extends AbstractTableGateway {

    /**
     * Nom de la table dans la base de données
     *
     * @var string $table
     */
    protected $table = 'rh_prime';

    /**
     * Constructeur de la Classe
     * 
     * @param \RHX\Model\Table\Adapter $adapter
     */
    public function __construct(Adapter $adapter) {
	$this->adapter			 = $adapter;
	$this->resultSetPrototype	 = new ResultSet();
	$this->resultSetPrototype->setArrayObjectPrototype(new Prime());
	$this->initialize();
    }

    /**
     * Tous les Primes de la table
     *
     * @param string $order Ordre d'affichage
     * @return type
     */
    public function getAll($order = 'id ASC') {
	return $this->select(function(Select $select) use($order) {
			    $select->order($order);
			});
    }
    
    /**
     * Effacer une prime
     * 
     * @param int $id
     * @return int
     */
    public function erase($id) {
	return $this->delete(array('id' => $id));
    }
    
    /**
     * Sauvegarder une prime
     *
     * @param \RHX\Model\Object\Prime $prime
     * @return int Identifiant du prime
     * @throws \Exception
     */
    public function save(Prime $prime) {
	$data	 = array(
	    'libelle'	 => $prime->libelle,
            'valeur'	 => $prime->valeur,
	    'description'	 => $prime->description,
            'is_cp'	 => $prime->is_cp,
	);
	$id	 = (int) $prime->id;
	if ($id == 0) {
	    $this->insert($data);

	    return $this->getLastInsertValue();
	}
	elseif ($this->get($id)) {
	    $this->update($data, array('id' => $id));

	    return $id;
	}
	else {
	    throw new \Exception("Impossible de séléctionner la prime #$id");
	}
    }
}

